'use strict'

const { isObject } = require('@imooc-cli-dev/utils')
const formatPath= require('@imooc-cli-dev/format-path')

const pathExists = require('path-exists').sync;
const pkdDir = require('pkg-dir').sync
const fse = require('fs-extra');
const { getNpmLatestVersion, getDefaultRegistryUrl } = require('@imooc-cli-dev/get-npm-info')
const path = require('path');
const log = require('@imooc-cli-dev/log')
const npminstall = require('npminstall')

class Package {
  constructor(options) {
    if(!options) {
      throw new Error('使用Package必须要传入optionsoptions')
    }

    if(!isObject(options)) {
      throw new Error('传入的options必须是对象')
    }

    this.targetPath = options.targetPath;
    this.storePath = options.storePath;
    this.packageName = options.packageName;
    this.packageNameVersion = options.packageNameVersion;
    this.cacheFilePathPrefix = this.packageName.replace('/', '_');
  }

  async prepare() {
    if(this.storePath && !pathExists(this.storePath)) {
      fse.mkdirsSync(this.storePath);
    }

    if(this.packageNameVersion === 'latest') {
      this.packageNameVersion =  await getNpmLatestVersion(this.packageName)
    }
  }
  // 获取缓存的路径
  get cacheFilePath() {
    return path.resolve(this.storePath, `_${this.cacheFilePathPrefix}@${this.packageNameVersion}@${this.packageName}`)
  }

  get nowFileVersion() {
    return require(path.resolve(this.cacheFilePath, 'package.json')).version 
  }

  getSpecificCacheFilePath(packageNameVersion) {
    return path.resolve(this.storePath, `_${this.cacheFilePathPrefix}@${this.packageNameVersion}@${this.packageNameVersion}@${this.packageName}`)

  }

  async exists() {
    // 缓存后的文件 storePath是实际执行目录
    if(this.storePath) {
      await this.prepare()
      return pathExists(this.cacheFilePath)
    } else {
      return pathExists(this.targetPath)
    }
  }

  async install() {
    await this.prepare()
    return npminstall({
      root: this.targetPath,
      storeDir: this.storePath,
      registry: getDefaultRegistryUrl(),
      pkgs: [
        { 
          name: this.packageName,
          version: this.packageNameVersion
        }
      ]
      
    })
  }

  async update() {
    await this.prepare()
    // 1.获取最新的npm模块版本号
    const latestVersion = await getNpmLatestVersion(this.packageName);
    // 查询最新版本号对应的路径是否存在
    console.log(this.nowFileVersion, 'nowFileVersion')
    console.log(latestVersion, 'latestVersion')
    console.log(this.storePathh, 'this.this.storePath')
    console.log(this.packageName, 'packageName')



    const latestFilePath = this.getSpecificCacheFilePath(latestVersion)
    // 3. 如果不存在，则直接安装最新版本
    if(!pathExists(latestFilePath)) {
     await  npminstall({
        root: this.targetPath,
        storeDir: this.storePath,
        registry: getDefaultRegistryUrl(),
        pkgs: [
          { 
            name: this.packageName,
            version: latestVersion
          }
        ]
      })

      this.packageNameVersion = latestVersion;
    }
  }

  getRootFilePath() {
    function _getPath(targetPath) {
      const targetPkgDir = pkdDir(targetPath)
      if(targetPkgDir) {
        // 2. 获取package.json
        const pkgFile = require(path.resolve(targetPkgDir, 'package.json'));
        // 3. 寻找main
        if(pkgFile && pkgFile.main) {
        // 4. 路径的兼容
          return formatPath(path.resolve(targetPkgDir, pkgFile.main))
        }
      }
    }
    if(this.storePath) {
      // 1. 获取package.json所在的目录
     return _getPath(this.cacheFilePath)
    } else {
     return _getPath(this.targetPath)
    }

    return null
  }
}

module.exports = Package;
